package org.finesys.common.netty.websocket.stomp.support;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.finesys.common.netty.websocket.annotation.BeforeHandShake;
import org.finesys.common.netty.websocket.annotation.OnBinary;
import org.finesys.common.netty.websocket.annotation.OnClose;
import org.finesys.common.netty.websocket.annotation.OnError;
import org.finesys.common.netty.websocket.annotation.OnEvent;
import org.finesys.common.netty.websocket.annotation.OnMessage;
import org.finesys.common.netty.websocket.annotation.OnOpen;
import org.finesys.common.netty.websocket.exception.WebSocketException;
import org.finesys.common.netty.websocket.resolver.ByteMethodArgumentResolver;
import org.finesys.common.netty.websocket.resolver.EventMethodArgumentResolver;
import org.finesys.common.netty.websocket.resolver.HttpHeadersMethodArgumentResolver;
import org.finesys.common.netty.websocket.resolver.PathVariableMapMethodArgumentResolver;
import org.finesys.common.netty.websocket.resolver.PathVariableMethodArgumentResolver;
import org.finesys.common.netty.websocket.resolver.RequestParamMapMethodArgumentResolver;
import org.finesys.common.netty.websocket.resolver.RequestParamMethodArgumentResolver;
import org.finesys.common.netty.websocket.resolver.SessionMethodArgumentResolver;
import org.finesys.common.netty.websocket.resolver.TextMethodArgumentResolver;
import org.finesys.common.netty.websocket.resolver.ThrowableMethodArgumentResolver;
import org.finesys.common.netty.websocket.support.MethodArgumentResolver;
import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor;
import org.springframework.beans.factory.support.AbstractBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.MethodParameter;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.util.ObjectUtils;

import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.stomp.StompFrame;

public class StompWebSocketEndpointMethodMapping {

    /**
     * 参数名解析
     */
    private static final ParameterNameDiscoverer PARAMETER_NAME_DISCOVERER = new DefaultParameterNameDiscoverer();

    /**
     * 握手前方法回调
     */
    private final Method beforeHandshake;
    /**
     * 连接完成回调方法
     */
    private final Method onOpen;

    /**
     * 连接关闭回调方法
     */
    private final Method onClose;

    /**
     * 连接错误回调方法
     */
    private final Method onError;

    /**
     * 接收到到Netty事件回调方法
     */
    private final Method onEvent;

    /**
     * 接收消息回调方法
     */
    private final Method onMessage;

    /**
     * 接收二进制消息回调方法
     */
    private final Method onBinary;


    /**
     * 握手前回调方法参数
     */
    private final MethodParameter[] beforeHandshakeParameters;

    /**
     * 连接建立回调方法参数
     */
    private final MethodParameter[] onOpenParameters;

    /**
     * 连接关闭方法参数
     */
    private final MethodParameter[] onCloseParameters;

    /**
     * 连接错误方法参数
     */
    private final MethodParameter[] onErrorParameters;

    /**
     * 接收字符串消息回调方法参数
     */
    private final MethodParameter[] onMessageParameters;

    /**
     * 接收二进制消息回调方法参数
     */
    private final MethodParameter[] onBinaryParameters;

    /**
     * 接收Netty事件回调方法参数
     */
    private final MethodParameter[] onEventParameters;

    /**
     * 握手前回调方法参数解析
     */
    private final MethodArgumentResolver[] beforeHandshakeArgResolvers;

    /**
     * 连接建立方法参数解析
     */
    private final MethodArgumentResolver[] onOpenArgResolvers;

    /**
     * 连接关闭方法参数解析
     */
    private final MethodArgumentResolver[] onCloseArgResolvers;

    /**
     * 连接错误方法参数解析
     */
    private final MethodArgumentResolver[] onErrorArgResolvers;

    /**
     * 接收到字符串消息参数方法参数解析
     */
    private final MethodArgumentResolver[] onMessageArgResolvers;

    /**
     * 接收到二进制消息方法参数解析
     */
    private final MethodArgumentResolver[] onBinaryArgResolvers;

    /**
     * 接收到Netty事件消息方法参数解析
     */
    private final MethodArgumentResolver[] onEventArgResolvers;
    /**
     * 标识了@WebSocketEndpoint注解的端点类
     */
    private final Class<?> webSocketEndpointClass;

    private final ApplicationContext applicationContext;

    private final AbstractBeanFactory beanFactory;

    public StompWebSocketEndpointMethodMapping(Class<?> webSocketEndpointClazz, ApplicationContext applicationContext, AbstractBeanFactory beanFactory) throws WebSocketException {
        this.webSocketEndpointClass = webSocketEndpointClazz;
        this.applicationContext = applicationContext;
        this.beanFactory = beanFactory;
        Method handshake = null;
        Method open = null;
        Method close = null;
        Method error = null;
        Method message = null;
        Method binary = null;
        Method event = null;
        Method[] methods = webSocketEndpointClass.getDeclaredMethods();
        Class<?> currentClazz = webSocketEndpointClass;
        while (!currentClazz.equals(Object.class)) {
            //当前类的声明方法
            Method[] currentClazzMethods = currentClazz.getDeclaredMethods();
            //遍历方法获取添加了注解的方法
            for (Method method : currentClazzMethods) {
                if (method.getAnnotation(BeforeHandShake.class) != null) {
                    checkPublic(method);
                    if (handshake == null) {
                        handshake = method;
                    } else {
                        // （1）说明了一个类中多个方法带有BeforeHandshake注解
                        // （2）说明了不是父类BeforeHandshake方法的重写
                        if (currentClazz == webSocketEndpointClazz || !isMethodOverride(handshake, method)) {
                            throw new WebSocketException("重复添加注解：@BeforeHandshake");
                        }
                    }
                } else if (method.getAnnotation(OnOpen.class) != null) {
                    checkPublic(method);

                    if (open == null) {
                        open = method;
                    } else {
                        // （1）说明了一个类中多个方法带有OnOpen注解 （2）说明了不是父类OnOpen方法的重写
                        if (currentClazz == webSocketEndpointClazz || !isMethodOverride(open, method)) {
                            throw new WebSocketException("重复添加注解: @OnOpen");
                        }
                    }
                } else if (method.getAnnotation(OnClose.class) != null) {
                    checkPublic(method);

                    if (close == null) {
                        close = method;
                    } else {
                        // （1）说明了一个类中多个方法带有OnClose注解 （2）说明了不是父类OnClose方法的重写
                        if (currentClazz == webSocketEndpointClazz || !isMethodOverride(close, method)) {
                            throw new WebSocketException("重复添加注解: @OnClose");
                        }
                    }
                } else if (method.getAnnotation(OnError.class) != null) {
                    checkPublic(method);

                    if (error == null) {
                        error = method;
                    } else {
                        // （1）说明了一个类中多个方法带有OnError注解 （2）说明了不是父类OnError方法的重写
                        if (currentClazz == webSocketEndpointClazz || !isMethodOverride(error, method)) {
                            throw new WebSocketException("重复添加注解: @OnError");
                        }
                    }
                } else if (method.getAnnotation(OnMessage.class) != null) {
                    checkPublic(method);

                    if (message == null) {
                        message = method;
                    } else {
                        // （1）说明了一个类中多个方法带有OnMessage注解 （2）说明了不是父类OnMessage方法的重写
                        if (currentClazz == webSocketEndpointClazz || !isMethodOverride(message, method)) {
                            throw new WebSocketException("重复添加注解: @onMessage");
                        }
                    }
                } else if (method.getAnnotation(OnBinary.class) != null) {
                    checkPublic(method);

                    if (binary == null) {
                        binary = method;
                    } else {
                        // （1）说明了一个类中多个方法带有OnBinary注解 （2）说明了不是父类OnBinary方法的重写
                        if (currentClazz == webSocketEndpointClazz || !isMethodOverride(binary, method)) {
                            throw new WebSocketException("重复添加注解: @OnBinary");
                        }
                    }
                } else if (method.getAnnotation(OnEvent.class) != null) {
                    checkPublic(method);

                    if (event == null) {
                        event = method;
                    } else {
                        if (currentClazz == webSocketEndpointClazz || !isMethodOverride(event, method)) {
                            throw new WebSocketException("重复添加注解: @OnEvent");
                        }
                    }
                }
            }

            // 继续获取父类信息
            currentClazz = currentClazz.getSuperclass();
        }
        // 父类标注了注解但是此websocket端点未标注此注解 取消标记
        if (handshake != null && handshake.getDeclaringClass() != webSocketEndpointClazz) {
            if (isOverrideWithoutAnnotation(methods, handshake, BeforeHandShake.class)) {
                handshake = null;
            }
        }
        if (open != null && open.getDeclaringClass() != webSocketEndpointClazz) {
            if (isOverrideWithoutAnnotation(methods, open, OnOpen.class)) {
                open = null;
            }
        }
        if (close != null && close.getDeclaringClass() != webSocketEndpointClazz) {
            if (isOverrideWithoutAnnotation(methods, close, OnClose.class)) {
                close = null;
            }
        }
        if (error != null && error.getDeclaringClass() != webSocketEndpointClazz) {
            if (isOverrideWithoutAnnotation(methods, error, OnError.class)) {
                error = null;
            }
        }
        if (message != null && message.getDeclaringClass() != webSocketEndpointClazz) {
            if (isOverrideWithoutAnnotation(methods, message, OnMessage.class)) {
                message = null;
            }
        }
        if (binary != null && binary.getDeclaringClass() != webSocketEndpointClazz) {
            if (isOverrideWithoutAnnotation(methods, binary, OnBinary.class)) {
                binary = null;
            }
        }
        if (event != null && event.getDeclaringClass() != webSocketEndpointClazz) {
            if (isOverrideWithoutAnnotation(methods, event, OnEvent.class)) {
                event = null;
            }
        }
        this.beforeHandshake = handshake;
        this.onOpen = open;
        this.onClose = close;
        this.onError = error;
        this.onMessage = message;
        this.onBinary = binary;
        this.onEvent = event;
        // 获取方法参数
        beforeHandshakeParameters = getParameters(beforeHandshake);
        onOpenParameters = getParameters(onOpen);
        onCloseParameters = getParameters(onClose);
        onMessageParameters = getParameters(onMessage);
        onErrorParameters = getParameters(onError);
        onBinaryParameters = getParameters(onBinary);
        onEventParameters = getParameters(onEvent);

        // 获取方法参数解析器
        beforeHandshakeArgResolvers = getResolvers(beforeHandshakeParameters);
        onOpenArgResolvers = getResolvers(onOpenParameters);
        onCloseArgResolvers = getResolvers(onCloseParameters);
        onMessageArgResolvers = getResolvers(onMessageParameters);
        onErrorArgResolvers = getResolvers(onErrorParameters);
        onBinaryArgResolvers = getResolvers(onBinaryParameters);
        onEventArgResolvers = getResolvers(onEventParameters);
    }

    private MethodArgumentResolver[] getResolvers(MethodParameter[] parameters) throws WebSocketException {
        MethodArgumentResolver[] methodArgumentResolvers = new MethodArgumentResolver[parameters.length];
        List<MethodArgumentResolver> resolverList = getDefaultResolvers();
        for (int i = 0; i < parameters.length; i++) {
            MethodParameter methodParameter = parameters[i];
            for (MethodArgumentResolver resolver : resolverList) {
                if (resolver.support(methodParameter)) {
                    methodArgumentResolvers[i] = resolver;
                    break;
                }
            }
            if (methodArgumentResolvers[i] == null) {
                throw new WebSocketException("参数无法解析 : " + methodParameter.getParameterName());
            }
        }
        return methodArgumentResolvers;
    }

    /**
     * 默认方法参数解析器
     *
     * @return List<MethodArgumentResolver>
     */
    private List<MethodArgumentResolver> getDefaultResolvers() {
        List<MethodArgumentResolver> list = new ArrayList<>();
        list.add(new SessionMethodArgumentResolver());
        list.add(new HttpHeadersMethodArgumentResolver());
        list.add(new TextMethodArgumentResolver());
        list.add(new ThrowableMethodArgumentResolver());
        list.add(new ByteMethodArgumentResolver());
        list.add(new RequestParamMapMethodArgumentResolver());
        list.add(new RequestParamMethodArgumentResolver(beanFactory));
        list.add(new PathVariableMapMethodArgumentResolver());
        list.add(new PathVariableMethodArgumentResolver(beanFactory));
        list.add(new EventMethodArgumentResolver(beanFactory));
        return list;
    }

    private MethodParameter[] getParameters(Method method) {
        if (method == null) {
            return new MethodParameter[0];
        }
        int paramsCount = method.getParameterCount();
        MethodParameter[] result = new MethodParameter[paramsCount];
        for (int i = 0; i < paramsCount; i++) {
            MethodParameter methodParameter = new MethodParameter(method, i);
            methodParameter.initParameterNameDiscovery(PARAMETER_NAME_DISCOVERER);
            result[i] = methodParameter;
        }
        return result;
    }

    private boolean isOverrideWithoutAnnotation(Method[] methods, Method supperClazzMethod, Class<? extends Annotation> annotation) {
        for (Method method : methods) {
            // 父类方法上添加了注解且子类重写方法上不具有此注解
            if (isMethodOverride(method, supperClazzMethod) && method.getAnnotation(annotation) == null) {
                return true;
            }
        }
        return false;
    }

    /**
     * 检查是否公共方法
     */
    private void checkPublic(Method method) throws WebSocketException {
        if (!Modifier.isPublic(method.getModifiers())) {
            throw new WebSocketException("methodNotPublic:" + method.getName());
        }
    }

    /**
     * 判断是否重载方法
     */
    private boolean isMethodOverride(Method handshake, Method method) {
        return (handshake.getName()).equals(method.getName()) && handshake.getReturnType().equals(method.getReturnType()) && Arrays.equals(handshake.getParameterTypes(), method.getParameterTypes());
    }

    /**
     * 获取WebSocket端点实例。
     * <p>
     * 使用反射机制创建WebSocket端点类的实例，并通过Spring的AutowiredAnnotationBeanPostProcessor处理依赖注入。
     *
     * @return WebSocket端点实例。
     * @throws NoSuchMethodException     如果端点类没有无参构造函数，将抛出此异常。
     * @throws InvocationTargetException 如果构造函数或初始化块抛出异常，将抛出此异常。
     * @throws InstantiationException    如果无法实例化端点类，将抛出此异常。
     * @throws IllegalAccessException    如果无法访问端点类的构造函数，将抛出此异常。
     */
    Object getEndpointInstance() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Object instance = webSocketEndpointClass.getDeclaredConstructor().newInstance();
        AutowiredAnnotationBeanPostProcessor postProcessor = applicationContext.getBean(AutowiredAnnotationBeanPostProcessor.class);
        postProcessor.postProcessProperties(null, instance, null);
        return instance;
    }

    public Method getBeforeHandshake() {
        return beforeHandshake;
    }

    public Method getOnOpen() {
        return onOpen;
    }

    public Method getOnClose() {
        return onClose;
    }

    public Method getOnError() {
        return onError;
    }

    public Method getOnEvent() {
        return onEvent;
    }

    public Method getOnMessage() {
        return onMessage;
    }

    public Method getOnBinary() {
        return onBinary;
    }

    public MethodArgumentResolver[] getBeforeHandshakeArgResolvers() {
        return beforeHandshakeArgResolvers;
    }

    public MethodArgumentResolver[] getOnOpenArgResolvers() {
        return onOpenArgResolvers;
    }

    public MethodArgumentResolver[] getOnCloseArgResolvers() {
        return onCloseArgResolvers;
    }

    public MethodArgumentResolver[] getOnErrorArgResolvers() {
        return onErrorArgResolvers;
    }

    public MethodArgumentResolver[] getOnMessageArgResolvers() {
        return onMessageArgResolvers;
    }

    public MethodArgumentResolver[] getOnBinaryArgResolvers() {
        return onBinaryArgResolvers;
    }

    public MethodArgumentResolver[] getOnEventArgResolvers() {
        return onEventArgResolvers;
    }

    public Object[] getBeforeHandshakeArgs(Channel channel, StompFrame request) throws Exception {
        return getMethodArgumentValues(channel, request, beforeHandshakeParameters, beforeHandshakeArgResolvers);
    }


    public Object[] getOnOpenArgs(Channel channel, StompFrame request) throws Exception {
        return getMethodArgumentValues(channel, request, onOpenParameters, onOpenArgResolvers);
    }


    public Object[] getOnCloseArgs(Channel channel) throws Exception {
        return getMethodArgumentValues(channel, null, onOpenParameters, onOpenArgResolvers);
    }

    public Object[] getOnErrorArgs(Channel channel, Throwable throwable) throws Exception {
        return getMethodArgumentValues(channel, throwable, onOpenParameters, onOpenArgResolvers);
    }

    public Object[] getOnMessageArgs(Channel channel, TextWebSocketFrame textWebSocketFrame) throws Exception {
        return getMethodArgumentValues(channel, textWebSocketFrame, onOpenParameters, onOpenArgResolvers);
    }

    public Object[] getOnBinaryArgs(Channel channel, BinaryWebSocketFrame binaryWebSocketFrame) throws Exception {
        return getMethodArgumentValues(channel, binaryWebSocketFrame, onOpenParameters, onOpenArgResolvers);
    }

    public Object[] getOnEventArgs(Channel channel, Object evt) throws Exception {
        return getMethodArgumentValues(channel, evt, onEventParameters, onEventArgResolvers);
    }

    /**
     * 获取方法参数的值
     *
     * @param channel    通道对象
     * @param object     目标对象
     * @param parameters 方法参数数组
     * @param resolvers  方法参数解析器数组
     * @return 方法参数值数组，如果参数或解析器为空，或者参数和解析器数量不匹配，则返回null
     * @throws Exception 如果在解析参数时发生异常
     */
    private Object[] getMethodArgumentValues(Channel channel, Object object, MethodParameter[] parameters, MethodArgumentResolver[] resolvers) throws Exception {
        if (ObjectUtils.isEmpty(parameters) || ObjectUtils.isEmpty(resolvers)) {
            return null;
        }
        if (parameters.length != resolvers.length) {
            return null;
        }
        Object[] objects = new Object[parameters.length];
        for (int i = 0; i < parameters.length; i++) {
            MethodParameter methodParameter = parameters[i];
            MethodArgumentResolver resolver = resolvers[i];
            Object arg = resolver.resolveArgument(methodParameter, channel, objects);
            objects[i] = arg;
        }
        return objects;
    }
}
